// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css';
import App from './App'
import router from './router'
/*引入store*/
import store from '../store'
import axios from 'axios'//第一种可以调用ajax的方法

import global from './global'//引入全局变量页面
import Qs from 'qs'

// import Export2Excel from './vendor/Export2Excel.js'
// import VCharts from 'v-charts'
// import VeLine from 'v-charts/lib/line'
import common from './assets/js/common'//引入封装的公共方法
import exportExcel from './assets/js/exportExcel'//引入封装的公共方法

import exportPdf from './assets/js/exportPdf'
import exportPdfContract from './assets/js/exportPdfContract'
import Print from './assets/js/print'

import Blob from "./excel/Blob";
import Export2Excel from "./excel/Export2Excel";

import Bus from './assets/js/Bus'
import CryptoJs from './assets/js/cryptojs.js'; //  加解密

import {Message} from 'element-ui'
// 分页组件
import Pagination from "@/components/Pagination";
// Vue.use(VCharts)
// Vue.use(VeLine)

/*var proxy = require('http-proxy-middleware');


Vue.use('/api', proxy({target: 'http://61.163.210.94:3000', changeOrigin: true}));*/



import { compress } from './utils/compress'
import { parseTime,resetForm,download } from "@/utils/index";
import  modal  from "@/utils/modal";
import errorCode from '@/utils/errorCode'


//引入vuex
//import vuex from 'vuex'
//Vue.use(vuex)

// Vue.prototype.excel = Export2Excel;
// Vue.use(Message)
Vue.config.productionTip = false
Vue.use(ElementUI);//调用elementUI
Vue.use(Print) // 注册

Vue.prototype.axios = axios;
Vue.prototype.GLOBAL = global;
Vue.prototype.Qs = Qs;
Vue.prototype.$http = common;
Vue.prototype.$export = exportExcel;

Vue.prototype.$pdf = exportPdf;
Vue.prototype.$pdfContract = exportPdfContract;

// Vue.prototype.$Print = Print;
Vue.prototype.Bus = Bus;
Vue.prototype.CryptoJs = CryptoJs;

Vue.prototype.$message=Message
Vue.prototype.$compress=compress
Vue.prototype.parseTime = parseTime
Vue.prototype.resetForm = resetForm
Vue.prototype.$modal = modal
Vue.prototype.download = download



//全局组件挂载
Vue.component('Pagination', Pagination)

//Vue.use(common);//调用elementUI

// 全局路由构造函数，判断是否登录和要跳转到页面
router.beforeEach((to, from, next) => {
  if (to.matched.some(m => m.meta.requireAuth)) {    // 需要登录
    //console.log(m.meta)
   // if(window.localStorage.token && window.localStorage.isLogin === '1'){
    if(window.localStorage.token){
      next()
    } else if (to.path != '/' || to.path != '/login' || to.path != '/403') {
      let token = window.localStorage.token;
      if (token == 'null' || token == '' || token == undefined){
          next({path: '/'})
          ElementUI.Message({
	        	type: 'info',
	       	 	message: '检测到您还未登录,请登录后操作！'
	      	});   
      }
    } else {
      next()
    }
  
  } else {   // 不需要登录
    next()
  }
  
})



// axios.defaults.timeout =  6000;
//添加请求拦截器
axios.interceptors.request.use(
  config =>{
    if(store.state.token){
      config.headers.common['Authorization'] =store.state.token
    }
    return config;
  },
  error =>{
    //对请求错误做什么
    return Promise.reject(error);
  })

//http reponse响应拦截器
axios.interceptors.response.use(
  response =>{
    console.log(response)
    // 未设置状态码则默认成功状态
    const code = response.data.code || 200;
    // 获取错误信息
    const msg = errorCode[code] || response.data.msg || errorCode['default']
    if (code === 401) {
      localStorage.removeItem('token');
      router.replace({
        path: '/login',
        query: {redirect: router.currentRoute.fullPath}//登录成功后跳入浏览的当前页面
      })
      return Promise.reject('无效的会话，或者会话已过期，请重新登录。')
    } else if (code === 500) {
      Message({
        message: msg,
        type: 'error'
      })
      return Promise.reject(new Error(msg))
    } else if (code !== 200) {
      Notification.error({
        title: msg
      })
      return Promise.reject('error')
    } else {
      return response
    }
  },
  error=>{
    console.log('err' + error)
    let { message } = error;
    if (message == "Network Error") {
      message = "后端接口连接异常";
    }
    else if (message.includes("timeout")) {
      message = "系统接口请求超时";
    }
    else if (message.includes("Request failed with status code")) {
      message = "系统接口" + message.substr(message.length - 3) + "异常";
    }
    Message({
      message: message,
      type: 'error',
      duration: 5 * 1000
    })
    /*** 
    if(error && error.response){
      switch(error.response.status){
        
        case 400: error.message = '请求错误(400)' ; break;
        //case 401: error.message = '未授权，请重新登录(401)'; break;
         case 403: error.message = '拒绝访问(403)'; break;
        
        //case 403: error.message = '拒绝访问(403)'; ElementUI.Message.error(error.response.data.detail);router.replace('/'); localStorage.clear(); break;
        case 404: error.message = '请求出错(404)'; break;
        case 408: error.message = '请求超时(408)'; break;
        case 500: error.message = '服务器错误(500)'; break;
        case 501: error.message = '服务未实现(501)'; break;
        case 502: error.message = '网络错误(502)'; break;
        case 503: error.message = '服务不可用(503)'; break;
        case 504: error.message = '网络超时(504)'; break;
        case 505: error.message = 'HTTP版本不受支持(505)'; break;
        
        case 401:
          localStorage.removeItem('token');
          router.replace({
            //path: '/index',
            path: '/login',
            query: {redirect: router.currentRoute.fullPath}//登录成功后跳入浏览的当前页面
          })
        case 404:
          localStorage.removeItem('token');
          router.replace({
            path: '/login',
            query: {redirect: router.currentRoute.fullPath}//登录成功后跳入浏览的当前页面
          })
          default: error.message = `连接出错(${error.response.status})!`;
        console.log(err)
      }
      console.log('---->',err.message)
    }else{
      error.message = '连接服务器失败!'
    } 
    ****/
    return Promise.reject(error)
  })
  // 时间戳转换
  Vue.filter('dateFormat', function(originVal) {
    const dt = new Date(originVal)
  
    const y = dt.getFullYear()
    const m = (dt.getMonth() + 1 + '').padStart(2, '0')
    const d = (dt.getDate() + '').padStart(2, '0')
  
    const hh = (dt.getHours() + '').padStart(2, '0')
    const mm = (dt.getMinutes() + '').padStart(2, '0')
    const ss = (dt.getSeconds() + '').padStart(2, '0')
  
    return `${y}-${m}-${d} ${hh}:${mm}:${ss}`
  })

  //  版本--缓存问题
  const VUE_APP_VERSION = require('../package.json').version;
  const vers = window.localStorage.getItem("Version");
  if(VUE_APP_VERSION != vers){
    localStorage.clear()
    window.localStorage.setItem("Version", VUE_APP_VERSION);
    location.reload()
  }

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  store,
  components: { App },
  template: '<App/>'   
})
